package lagrangeinterpolation;

import java.util.ArrayList;

/**
 *
 * @author PavelsKletnojs
 */
public class Main {
    public static void main(String[] args) {
	try{
	    ReadFile rf = new ReadFile();
	    ArrayList<Double> x = rf.matrixAsList.get(0);
	    ArrayList<Double> y = rf.matrixAsList.get(1);

	    
	    System.out.print("L(x) =");
	    for(int i = 0; i<y.size(); i++){
		System.out.print(" + " + y.get(i) + "*l" + i + "(x)");
	    }
	    System.out.println("\n");

	    ArrayList<Polynomial> polyArray = new ArrayList<Polynomial>();
	    Polynomial lagrangePoly = new Polynomial(0.0);
	    Polynomial poly;
	    
	    //Calculate final polynom
	    for(int i = 0; i<y.size(); i++){
		poly = new Polynomial(1.0);
		polyArray.add(poly);
		double denom = 1;
		
		//Calculate current polynom
		for(int j = 0; j<y.size(); j++){
		    if(i != j){
			denom *= (i - j);
			poly = poly.multiply(new Polynomial(1.0, -(double)j-1));
		    }
		}

		System.out.print("l" + i + "(x) = " + poly.toString());
		System.out.println("\t Denom: " + denom);

		// See rule how to calculate lagrange polynomial
		lagrangePoly = lagrangePoly.plus(poly.divide(denom).multiply(y.get(i)));
	    }

	    System.out.println("\nLagrange Polynomial: ");
	    System.out.println(lagrangePoly);

	    System.out.println("\nFunction in x = 4.5 (as an example): ");
	    System.out.println(lagrangePoly.getFunction(4.5));
	    
	}
	catch(Exception e){
	    System.out.println(e);
	}
    }	
}
